//
//  SubmitWorkViewController.m
//  Learn
//
//  Created by 迟建国 on 2024/4/5.
//  Copyright © 2024 迟建国. All rights reserved.
//

#import "SubmitWorkViewController.h"
#import "SubmitWorkCollectionViewCell.h"
#import "TestFinishViewController.h"
#import "HomeRequest.h"

@interface SubmitWorkViewController ()<UICollectionViewDelegate, UICollectionViewDataSource>
@property (nonatomic, strong) UICollectionView *collectionView;
@property (nonatomic, strong) PcmPlayer *pcmPlay;

@end

@implementation SubmitWorkViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = rgba(245, 245, 245, 1);
    [self setUI];
    [self setNavUI];
}

- (void)setUI {
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
    layout.sectionInset = UIEdgeInsetsMake(10, 0, 10, 0);
    layout.minimumLineSpacing = 10;
    UICollectionView *collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, NavigationBarHeight, SCREEN_W, SCREEN_H - NavigationBarHeight - 60 - SafeAreaBottomHeight) collectionViewLayout:layout];
    collectionView.backgroundColor = UIColor.clearColor;
    collectionView.delegate = self;
    collectionView.dataSource = self;
    collectionView.showsVerticalScrollIndicator = NO;
    collectionView.showsHorizontalScrollIndicator = NO;
//    collectionView.alwaysBounceVertical = NO;
//    self.extendedLayoutIncludesOpaqueBars = YES;
    if (@available(iOS 11.0, *)) {
        collectionView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    }
    [collectionView registerNib:[UINib nibWithNibName:@"SubmitWorkCollectionViewCell" bundle:[NSBundle mainBundle]] forCellWithReuseIdentifier:@"SubmitWorkCollectionViewCell"];

    [self.view addSubview:collectionView];
    self.collectionView = collectionView;
    
    UIButton *doneBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    doneBtn.layer.cornerRadius = 22.5;
    doneBtn.layer.masksToBounds = YES;
    doneBtn.backgroundColor = rgba(41, 241, 156, 1);
    [doneBtn setTitle:@"交作业" forState:UIControlStateNormal];
    [doneBtn setTitleColor:UIColor.whiteColor forState:UIControlStateNormal];
    doneBtn.titleLabel.font = [UIFont fontWithName:@"PingFangSC-Semibold" size:18];
    [doneBtn addTarget:self action:@selector(done) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:doneBtn];
    [doneBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.view.mas_left).offset(10);
        make.right.equalTo(self.view.mas_right).offset(-10);
        make.bottom.equalTo(self.view.mas_bottom).offset(-SafeAreaBottomHeight - 10);
        make.height.offset(45);
    }];
}

- (void)done {
    if ([self.type isEqualToString:@"单词"]) {
        NSMutableArray *zuoye = [NSMutableArray arrayWithCapacity:1];
        for (TextBookUnitWordModel *wordModel in self.dataArr) {
            NSDictionary *param1 = @{
                @"tid":wordModel.wId,
                @"score":@(wordModel.totalScore),
                @"source":wordModel.recordPath.length ? wordModel.recordPath : @""
            };
            NSLog(@"%@",param1);
            [zuoye addObject:param1];
        }
        NSString *jsonstr = [[NSString alloc] initWithData:[NSJSONSerialization dataWithJSONObject:[zuoye copy] options:NSJSONWritingPrettyPrinted error:nil] encoding:NSUTF8StringEncoding];

        NSDictionary *param = @{
            @"mission_id":self.unitWordModel.parentVersionId,
            @"score":@"0",
            @"question_type":@"3",
            @"question_num":@(self.dataArr.count),
            @"source_id":self.unitWordModel.versionId,
            @"json":jsonstr
        };
        [HomeRequest submitTingshuoworkWith:param result:^(NSDictionary *data) {
            NSLog(@"%@",data);
            if (data) {
                TestFinishViewController *vc = [[TestFinishViewController alloc] init];
                vc.data = data;
                [self.navigationController pushViewController:vc animated:YES];
            }
        }];
    } else {
        NSMutableArray *zuoye = [NSMutableArray arrayWithCapacity:1];
        for (TextBookUnitTextModel *textModel in self.dataArr) {
            NSDictionary *param1 = @{
                @"tid":textModel.versionId,
                @"score":@(textModel.totalScore),
                @"source":textModel.recordPath.length ? textModel.recordPath : @""
            };
            NSLog(@"%@",param1);
            [zuoye addObject:param1];
        }
        NSString *jsonstr = [[NSString alloc] initWithData:[NSJSONSerialization dataWithJSONObject:[zuoye copy] options:NSJSONWritingPrettyPrinted error:nil] encoding:NSUTF8StringEncoding];

        NSDictionary *param = @{
            @"mission_id":self.unitWordModel.parentVersionId,
            @"score":@"0",
            @"question_type":@"3",
            @"question_num":@(self.dataArr.count),
            @"source_id":self.unitWordModel.versionId,
            @"json":jsonstr
        };
        [HomeRequest submitTingshuoworkWith:param result:^(NSDictionary *data) {
            NSLog(@"%@",data);
            if (data) {
                TestFinishViewController *vc = [[TestFinishViewController alloc] init];
                vc.data = data;
                [self.navigationController pushViewController:vc animated:YES];
            }
        }];
    }
}

- (void)setNavUI {
    UIView *nav = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_W, NavigationBarHeight)];
    nav.backgroundColor = rgba(245, 245, 245, 1);
    [self.view addSubview:nav];
//    self.nav = nav;
    
    UIButton *backBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [backBtn setImage:[UIImage imageNamed:@"icon_back"] forState:UIControlStateNormal];
    [backBtn addTarget:self action:@selector(back) forControlEvents:UIControlEventTouchUpInside];
    [nav addSubview:backBtn];
    [backBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(nav.mas_left).offset(5);
        make.bottom.equalTo(nav.mas_bottom);
        make.width.offset(50);
        make.height.offset(44);
    }];
    
    UILabel *titleL = [[UILabel alloc] init];
    titleL.text = self.unitWordModel.moduleName;
    titleL.font = [UIFont fontWithName:@"PingFangSC-Semibold" size:16];
    titleL.textColor = rgb(51, 51, 51);
    titleL.textAlignment = NSTextAlignmentCenter;
    [nav addSubview:titleL];
    [titleL mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(nav.mas_bottom);
        make.centerX.equalTo(nav.mas_centerX);
        make.height.offset(44);
    }];
    
}

#pragma collectionView

- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
    return 1;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return self.dataArr.count;
}

- (__kindof UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    SubmitWorkCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"SubmitWorkCollectionViewCell" forIndexPath:indexPath];
    if (!cell) {
        cell = [[[NSBundle mainBundle]loadNibNamed:@"SubmitWorkCollectionViewCell" owner:self options:nil] lastObject];
    }
    if ([self.type isEqualToString:@"单词"]) {
        cell.wordModel = self.dataArr[indexPath.row];
    } else {
        cell.textModel = self.dataArr[indexPath.row];
    }
    cell.playBlock = ^{
        TextBookUnitWordModel *model = self.dataArr[indexPath.row];
        [self.pcmPlay stop];
        self.pcmPlay = [[PcmPlayer alloc] initWithFilePath:model.recordPath sampleRate:8000];
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [self.pcmPlay play];
        });
    };
    return cell;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
//    WrongQuestionDetailController *vc = [[WrongQuestionDetailController alloc] init];
//    [self.navigationController pushViewController:vc animated:YES];
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{
    return CGSizeMake(SCREEN_W - 20, 112);
}

- (void)back {
    [self.pcmPlay stop];
    [self.navigationController popViewControllerAnimated:YES];
}
- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:YES animated:YES];
}

- (void)viewWillDisappear:(BOOL)animated {
    [self.pcmPlay stop];
    [super viewWillDisappear:animated];
    [self.navigationController setNavigationBarHidden:NO animated:YES];
}

- (NSMutableArray *)dataArr {
    if (!_dataArr) {
        _dataArr = [NSMutableArray array];
    }
    return _dataArr;
}
@end
